<template>
<!--  户表抄表率统计页面-->
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height:96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
          <el-tree
            :default-expanded-keys="defaultExpandedKeys"
            :data="sheetsTreeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="sheetsCode"
            highlight-current
            v-loading="treeLoading"
            show-checkbox
            @check="getReadingRateList"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node"
                   style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                <!--                <div style="vertical-align: -0.15em;margin-right: 5px; display: block;">-->
                <!--                                   <el-icon-folder-checked  style="height: 1.1em;width: 1.1em" />-->
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>

                <!--                <i class="el-icon-menu" v-if="data.deviceType == 1" ></i>-->
                <!--                <i class="el-icon-s-grid" v-if="data.deviceType == 2" ></i>-->
                <!--                </div>-->
                <span>{{ node.label }}</span>
              </div>
            </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;display: flex;justify-content: space-between;">
          <div style="width: 80%;display: flex;">
            <div>
              <el-radio-group size="mini" v-model="queryParams.dateSpan" @input="getReadingRateList">
                <el-radio-button :label="1">昨天</el-radio-button>
                <el-radio-button :label="7">最近7天</el-radio-button>
                <el-radio-button :label="30">最近30天</el-radio-button>
              </el-radio-group>
            </div>

            <div style="margin-left: 10px;">
              <span style="font-size: 12px;margin-right: 5px;">抄表率</span>
              <el-input size="mini" style="width: 98px;" placeholder="起始值"
                        v-model="queryParams.rateFrom">
                <template slot="suffix">
                  <div style="margin-top: 6px;">%</div>
                </template>
              </el-input>
              <span style="font-size: 12px;margin:0 auto;">-</span>
              <el-input size="mini" style="width: 98px;" placeholder="结束值"
                        v-model="queryParams.rateTo">
                <template slot="suffix">
                  <div style="margin-top: 6px;">%</div>
                </template>
              </el-input>

              <el-button type="primary" icon="el-icon-search" size="mini" style="margin-left: 10px;"
                         @click="getReadingRateList">搜索
              </el-button>
            </div>
          </div>

          <div>
            <el-button type="primary" icon="el-icon-download" size="mini" style="margin-left: 10px;"
                       @click="handleExport">导出
            </el-button>
          </div>
        </div>

        <div style="margin-top: 5px;">
          <el-row :gutter="5">
            <el-col :span="24 / summaryData.length" v-for="item in summaryData">
              <SummaryItem :click-able="item.hasLink" :click-callback="item.callback" :label="item.label"
                           :value="item.value" :bg-color="item.bgColor" :icon="item.icon"/>
            </el-col>
          </el-row>

          <el-row style="margin-top: 10px;">
            <el-table size="mini" border :height="getAvailableHeight" style="width: 100%"
                      :data="readingRateData" v-loading="tableLoading" :default-sort="defaultSort"
                      @sort-change="handleSorterChange">
              <el-table-column type="index" label="#" width="40" align="center"/>
              <el-table-column prop="sheetsName" label="区域名称" align="center" sortable="custom"
                               :sort-orders="['ascending','descending']"/>
              <el-table-column prop="total" label="应抄水表总数（台）" align="center" sortable="custom"
                               :sort-orders="['ascending','descending']"/>
              <el-table-column prop="count" label="抄表成功总数（台）" align="center" sortable="custom"
                               :sort-orders="['ascending','descending']"/>
              <el-table-column prop="rate" label="抄表成功率(%)" align="center" sortable="custom"
                               :sort-orders="['ascending','descending']"/>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right"
                               width="80">
                <template slot-scope="scope">
                  <el-tooltip effect="dark" content="查看未抄回记录" placement="top">
                    <el-button
                      type="text"
                      icon="el-icon-view"
                      size="mini"
                      @click="handleViewMissing(scope.row)"
                    >
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-row>

          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getReadingRateList"
          />
        </div>
      </el-col>
    </el-row>

    <el-dialog title="未抄回记录" :visible.sync="missingOpen" append-to-body :close-on-click-modal="false"
               width="1200px">
      <el-table size="mini" border v-loading="loading" :data="terminalsFreezeXbWcViewList" :height="getAvailableHeight">
        <el-table-column label="#" align="center" type="index" width="50"/>
        <el-table-column label="区域名称" align="center" prop="sheetsName"/>
        <el-table-column label="区域编号" align="center" prop="sheetsCode"/>
        <el-table-column label="用户名称" align="center" prop="userName"/>
        <el-table-column label="用户编号" align="center" prop="userId"/>
        <el-table-column label="设备编号" align="center" prop="terminalId"/>
        <!--        <el-table-column label="用户手机号码" align="center" prop="userPhone"/>-->
        <el-table-column label="未上报日期" align="center" prop="freezeTime"/>
        <el-table-column label="最近上报时间" align="center" prop="readDate" width="180"/>
        <!--        <el-table-column label="水表读数" align="center" prop="totalFlow"/>-->
        <!--        <el-table-column label="阀门状态(0-关，1-开)" align="center" prop="valveState"/>-->
        <el-table-column label="预警描述" align="center" prop="description"/>
      </el-table>

      <pagination :total="missingTotal"
                  :page.sync="missingQueryParams.pageNum"
                  :limit.sync="missingQueryParams.pageSize"
                  @pagination="getMissingDataList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleExportMissingData">导 出</el-button>
        <el-button type="danger" @click="missingOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAreaTree } from "@/api/tree/index"
import {listMeterSheetsTree,} from "@/api/basedata/meterSheets";
import {listReadingRate,} from "@/api/analysis/meter/readingrate";
import {listMissingTerminalsFreezeXb} from '@/api/basedata/terminalsFreezeXbWcView'
import SummaryItem from '../components/SummaryItem.vue'

export default {
  name: 'ReadingRateXb',
  components: {
    SummaryItem
  },
  data() {
    return {
      defaultExpandedKeys: [],
      screenHeight: null,
      treeLoading: false,
      tableLoading: false,
      // 默认排序
      defaultSort: {prop: 'rate', order: 'descending'},
      // 区域树选项
      sheetsTreeList: [],
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      summaryData: [
        {
          label: '应抄水表总数(个)',
          key: 'totalAll',
          value: '0',
          bgColor: '#7c67d7',
          icon: 'el-icon-document',
          hasLink: false
        },
        {
          label: '抄表成功总数(个)',
          key: 'countAll',
          value: '0',
          bgColor: '#22b38f',
          icon: 'el-icon-document',
          hasLink: false
        },
        {
          label: '抄表成功率(%)',
          key: 'rateAll',
          value: '0%',
          bgColor: '#4ab4d5',
          icon: 'el-icon-s-data',
          hasLink: true,
          callback: () => {
            console.log('viewAllMissingData')
            this.missingOpen = true
            this.missingQueryParams.sheetsCode = this.$refs.tree.getCheckedKeys().join(',');
            this.getMissingDataList()
          }
        },
      ],
      radio4: '昨天',
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: '',
        dateSpan: 1,
        rateFrom: 0,
        rateTo: 100,
        systemFlag: '',
        loginUserId: '',
      },
      filterText: '',
      readingRateData: [],
      missingOpen: false,
      loading: false,
      missingTotal: 0,
      missingQueryParams: {
        pageNum: 1,
        pageSize: 20,
        sheetsCode: null,
      },
      terminalsFreezeXbWcViewList: [],
    }
  },
  methods: {
    // 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择区域查看数据!")
    },
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getReadingRateList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // let treeType = "0,1"
      // getAreaTree(treeType).then(response => {
      //   this.sheetsTreeList = response.data;
      //   this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if (this.sheetsTreeList.length === 0){
        this.treeLoading = false;
      }else{
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    /** 查询抄表率明细 */
    getReadingRateList() {
      this.checkSortColumn()
      if (this.$refs.tree.getCheckedKeys().length > 0) {
        this.tableLoading = true;
        this.queryParams.sheetsCode = this.$refs.tree.getCheckedKeys().join(',');
        this.queryParams.systemFlag = this.systemFlag
        this.queryParams.loginUserId = this.userId
        listReadingRate(this.queryParams).then(response => {
          if (response.data) {
            const data = response.data
            this.total = data.dataTotal;
            this.readingRateData = data.dataRows;
            this.summaryData.forEach(item => {
              item.value = data[item.key] + ''
            })
          }
          this.tableLoading = false;
        });
      }else {
        this.$modal.msgWarning("请至少选择一个区域!")
      }
    },
    getMissingDataList() {
      this.loading = true
      this.missingQueryParams.dateSpan = this.queryParams.dateSpan
      listMissingTerminalsFreezeXb(this.missingQueryParams).then(res => {
        this.loading = false
        this.terminalsFreezeXbWcViewList = res.rows
        this.missingTotal = res.total
      })
    },
    handleExportMissingData() {
      this.download('basedata/terminalsFreezeXbWcView/exportMissing', {
        ...this.missingQueryParams
      }, `未抄回记录数据.xlsx`)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('analysis/meter/exportReadingRate', {
        ...this.queryParams
      }, `抄表率统计数据.xlsx`)
    },
    handleViewMissing(row) {
      const {count, total, sheetsCode} = row
      if (count === total) {
        this.$message.info('暂无未抄回数据')
      } else {
        this.missingOpen = true
        this.missingQueryParams.sheetsCode = sheetsCode
        this.getMissingDataList()
      }
    },
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 308
    },
    userId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.tip();
    this.getTreeList()
    // this.getReadingRateList()
  }
}
</script>

<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

}
</style>
